<template>
  <transition name="module">
    <div v-if="!fetching && pagination?.total_page > 1" class="pagination">
      <ul class="pagination-list">
        <li class="item prev">
          <span class="symbol">-</span>
          <span>{{ isHotSort? "最热" : "最新" }}</span>
        </li>
        <li v-for="(item, index) in pagination.total_page" :key="index" class="item">
          <button class="pagination-btn" :class="{ actived: isActivePage(item), disabled: isActivePage(item) }" @click="handlePage(item)">
            {{ item }}
          </button>
        </li>
        <li class="item next">
          <span>{{ isHotSort? "最冷" : "最旧" }}</span>
          <span class="symbol">-</span>
        </li>
      </ul>
    </div>
  </transition>
</template>

<script>
  import { defineComponent, computed } from 'vue'

  export default defineComponent({
    name: 'CommentPagination',
    props: {
      fetching: {
        type: Boolean,
        required: true
      },
      sort: {
        type: Number,
        required: true
      },
      pagination: Object
    },
    setup(props, context) {
      const isHotSort = computed(() => props.sort === 2)
      const isActivePage = (index) => {
        return isHotSort.value
          ? index === props.pagination?.current_page
          : index === props.pagination?.total_page + 1 - props.pagination?.current_page
      }

      const handlePage = (page) => {
        if (!isActivePage(page)) {
          if (props.pagination) {
            context.emit("page",
              isHotSort.value
                ? page
                : props.pagination.total_page + 1 - page
            )
          }
        }
      }

      return {
        isHotSort,
        isActivePage,
        handlePage
      }
    }
  })
</script>

<style lang="scss" scoped>
  .pagination {
    margin-top: $lg-gap;

    > .pagination-list {
      margin: 0;
      padding: 0;
      display: flex;
      justify-content: center;
      list-style-type: none;

      > .item {
        $item-size: 2rem;
        margin: 0 0.5em;

        &.prev,
        &.next {
          display: inline-block;
          width: 4em;
          height: $item-size;
          line-height: $item-size;
          font-size: $font-size-small;
          text-align: center;
          color: $text-disabled;

          .symbol {
            margin: 0 $xs-gap;
          }

          &:hover {
            background: none;
          }
        }

        .pagination-btn {
          display: inline-block;
          width: $item-size;
          height: $item-size;
          line-height: $item-size;
          text-align: center;
          @include radius-box($mini-radius);
          @include background-transition();

          &.disabled {
            cursor: no-drop;
            opacity: .5;
          }

          &.actived,
          &:hover {
            background-color: $module-bg-darker-1;
          }
        }
      }
    }
  }
</style>
